<template>
  <div class="menu-edit">
    <el-card>
      <div class="card-header">
        <span>编辑菜单</span>
      </div>
      
      <el-form :model="menuForm" :rules="rules" ref="menuForm" label-width="120px">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="menuForm.menuName" placeholder="请输入菜单名称" maxlength="100"></el-input>
        </el-form-item>
        
        <el-form-item label="父菜单" prop="parentId">
          <el-select v-model="menuForm.parentId" placeholder="请选择父菜单">
            <el-option label="顶级菜单" value="0"></el-option>
            <el-option v-for="menu in parentMenuList" :key="menu.id" :label="menu.menuName" :value="menu.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜单路径" prop="path" v-if="menuForm.parentId !== 0">
          <el-input v-model="menuForm.path" placeholder="请输入菜单路径" maxlength="200"></el-input>
        </el-form-item>
        
        <el-form-item label="组件路径" prop="component" v-if="menuForm.parentId !== 0">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" maxlength="200"></el-input>
        </el-form-item>
        
        <el-form-item label="菜单图标">
          <el-input v-model="menuForm.icon" placeholder="请输入图标类名" maxlength="50"></el-input>
        </el-form-item>
        
        <el-form-item label="排序号" prop="sortOrder">
          <el-input v-model.number="menuForm.sortOrder" placeholder="请输入排序号" type="number" min="0"></el-input>
        </el-form-item>
        
        <el-form-item label="是否可见">
          <el-switch v-model="menuForm.isVisible" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        
        <el-form-item label="是否启用">
          <el-switch v-model="menuForm.isEnabled" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MenuEdit',
  data() {
    return {
      menuForm: {
        id: '',
        menuName: '',
        parentId: 0,
        path: '',
        component: '',
        icon: '',
        sortOrder: 0,
        isVisible: true,
        isEnabled: true
      },
      parentMenuList: [],
      rules: {
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { max: 100, message: '菜单名称不能超过100个字符', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入菜单路径', trigger: 'blur' },
          { max: 200, message: '菜单路径不能超过200个字符', trigger: 'blur' }
        ],
        component: [
          { required: true, message: '请输入组件路径', trigger: 'blur' },
          { max: 200, message: '组件路径不能超过200个字符', trigger: 'blur' }
        ],
        sortOrder: [
          { required: true, message: '请输入排序号', trigger: 'blur' },
          { type: 'number', min: 0, message: '排序号必须大于等于0', trigger: 'blur' }
        ]
      },
      originalMenuName: '',
      originalParentId: 0
    };
  },
  mounted() {
    const id = this.$route.query.id;
    if (id) {
      this.loadMenuDetail(id);
      this.loadParentMenus();
    } else {
      this.$message.error('菜单ID不能为空');
      this.$router.push('/menu');
    }
  },
  methods: {
    loadMenuDetail(id) {
      this.$api.menuApi.getById(id)
        .then(res => {
          const data = res && res.data || null;
          if (data) {
            this.menuForm = { ...data };
            this.originalMenuName = this.menuForm.menuName;
            this.originalParentId = this.menuForm.parentId;
          } else {
            this.$message.error('获取菜单详情失败');
            this.$router.push('/menu');
          }
        })
        .catch(error => {
          console.error('获取菜单详情失败:', error);
          this.$message.error('获取菜单详情失败: ' + error.message);
          this.$router.push('/menu');
        });
    },
    
    loadParentMenus() {
      this.$api.menuApi.getAll()
        .then(res => {
          // 排除当前菜单作为父菜单选项
          const menus = res && res.data || [];
          this.parentMenuList = menus.filter(menu => menu.id !== this.menuForm.id);
        })
        .catch(error => {
          console.error('获取父菜单列表失败:', error);
          this.$message.error('获取父菜单列表失败');
        });
    },
    
    handleSubmit() {
      this.$refs.menuForm.validate((valid) => {
        if (valid) {
          // 检查菜单名称是否已存在（排除当前菜单）
          this.$api.menuApi.getAll()
            .then(res => {
              const menus = res && res.data || [];
              const exists = menus.some(menu => 
                menu.menuName === this.menuForm.menuName && 
                menu.parentId === this.menuForm.parentId &&
                menu.id !== this.menuForm.id
              );
              
              if (exists) {
                this.$message.error('菜单名称已存在');
                return;
              }
              
              // 提交表单
              this.$api.menuApi.update(this.menuForm.id, this.menuForm)
                .then(() => {
                  this.$message.success('菜单更新成功');
                  this.$router.push('/menu');
                })
                .catch(error => {
                  console.error('更新菜单失败:', error);
                  this.$message.error('更新菜单失败: ' + error.message);
                });
            })
            .catch(error => {
              console.error('检查菜单名称失败:', error);
              // 继续提交，让后端进行验证
              this.$api.menuApi.update(this.menuForm.id, this.menuForm)
                .then(() => {
                  this.$message.success('菜单更新成功');
                  this.$router.push('/menu');
                })
                .catch(error => {
                  console.error('更新菜单失败:', error);
                  this.$message.error('更新菜单失败: ' + error.message);
                });
            });
        }
      });
    },
    
    handleCancel() {
      this.$router.push('/menu');
    }
  }
};
</script>

<style scoped>
.menu-edit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>